package com.qf.task;


import com.google.common.collect.HashMultimap;

import com.qf.entity.SysHumiture;
import com.qf.events.CommandEvent;
import com.qf.mapper.SysHumitureDao;
import com.qf.mapper.SysHumitureMapper;
import com.qf.websocket.MyCommandHandler;
import com.qf.websocket.MyHumiTempHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class HumitureTask {

    private SysHumitureMapper sysHumitureMapper;
    private SysHumitureDao sysHumitureDao;

    @Autowired
    public void setSysHumitureMapper(SysHumitureMapper sysHumitureMapper) {
        this.sysHumitureMapper = sysHumitureMapper;
    }

    @Autowired
    public void setSysHumitureDao(SysHumitureDao sysHumitureDao) {
        this.sysHumitureDao = sysHumitureDao;
    }

    @Scheduled(fixedRate = 90000)
    public void checkTemp() {
        System.err.println("开始计算温湿度的平均值了");

        HashMultimap<String, SysHumiture> humitureHashMultimap = MyHumiTempHandler.getHumitureHashMultimap();
        //将数据转成普通map
        Map<String, Collection<SysHumiture>> asMap = humitureHashMultimap.asMap();
        //临时的数据
        HashMap<String, Collection<SysHumiture>> linshbianliang = new HashMap<>(asMap);
        //将数据批量写入到数据库,清理最近的缓存
        CompletableFuture<Void> insert = CompletableFuture.runAsync(() -> {
            linshbianliang.forEach((id, hums) -> {
                hums.parallelStream().forEach(humiture -> sysHumitureDao.insert(humiture));

            });
        });
        //计算最近一段时间的平均温度是不是达到我们的阈值,到了的话 就开风扇,不到就关闭风扇
        CompletableFuture<Void> computer = CompletableFuture.runAsync(() -> {
            linshbianliang.forEach((id, hums) -> {
                //遍历每一个hashset, 拿到里面的每一个温湿度的对象,然后调用获取温度的方法,拿到温度,将所有的温度保存到一个集合中
                double avg = hums.parallelStream().mapToDouble(SysHumiture::getTemperature).summaryStatistics().getAverage();//当前的平均值
                System.err.println("设备:" + id + "计算出的平均值是:" + avg);

                CommandEvent commandEvent;
                if (avg >= 40) {
                    commandEvent = new CommandEvent("1234567890", "0");//开
                } else {
                    commandEvent = new CommandEvent("1234567890", "1");//关
                }
                MyCommandHandler.sendControl(commandEvent);

            });
        });

        CompletableFuture.allOf(insert, computer).thenRunAsync(() -> {
            //清空数据
            humitureHashMultimap.clear();
        });
    }
}
